#!/bin/sh

# Copyright 2014 Timothy Edward Baldwin

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# Create pid file directory
test -d test || mkdir test

# Kill old relays
start-stop-daemon --stop --oknodo --name navalis-relay --pidfile test/1.pid --retry 5
start-stop-daemon --stop --oknodo --name navalis-relay --pidfile test/2.pid --retry 5

# Kill old clients
for i in $(seq 3 10); do
  start-stop-daemon --stop --oknodo --name navalis --pidfile "test/${i}.pid" --retry 5
done

sleep 2

# Start relays
ip netns exec navalis-test-1 ./navalis-relay \
--interface-up="ip addr add dev 6a44_relay 10.10.10.10; ip addr add dev 6a44_relay 2001:db8:6a44::/48" \
--ipv4=10.10.10.10 --prefix=2001:db8:6a44:: --remote-ipv4=192.168.2.1  --pidfile=test/1.pid

ip netns exec navalis-test-2 ./navalis-relay \
--interface-up="ip addr add dev 6a44_relay 10.10.10.10; ip addr add dev 6a44_relay 2001:db8:6a44::/48" \
--ipv4=10.10.10.10 --prefix=2001:db8:6a44:: --remote-ipv4=192.168.2.2  --pidfile=test/2.pid

# Slow down relays
ip netns exec navalis-test-1 tc qdisc add dev 6a44_relay root netem delay 5ms
ip netns exec navalis-test-2 tc qdisc add dev 6a44_relay root netem delay 100ms

# Start the clients
for i in $(seq 3 10); do
  ip netns exec navalis-test-$i ./navalis --script=./navalis-script --relay 10.10.10.10 --pidfile "test/${i}.pid" &
done

sleep 2

# Make a file of client IPv6 addresses
(
  for i in $(seq 3 10); do
    ip netns exec navalis-test-$i ip addr show
  done
) | sed -e's/^.*inet6 \(2[^ ]*\)\/.*$/\1/;t;d' > test/ip_addresses

# Test connectivity with oping
for i in $(seq 3 10); do
  echo
  echo From namespace $i:
  sleep 1
  ip netns exec navalis-test-$i oping -6 -c1 -f test/ip_addresses | grep icmp
  sleep 1
  echo Again:
  ip netns exec navalis-test-$i oping -6 -c1 -f test/ip_addresses | grep icmp
done
